package com.tedu.springboot2307.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import com.tedu.springboot2307.entity.User;
import sun.plugin2.message.Serializer;

//user控制层
@Controller//支持注解
public class UserController {
    private static File userDir;

    static{
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }


    @RequestMapping("/regUser")//括号中内容与注册页面表单action的值一致
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册!!!");
        /*
            1:获取用户在注册页面表单中输入的注册信息
            2:将注册信息保存到硬盘上
            3:给用户回馈注册结果页面
         */
        //1获取表单提交上来的数据
        /*
            获取表单信息时，调用请求对象的方法:getParameter。调用时传入的参数要
            与页面表单中对应输入框的名字一致！
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);


        if(username==null || username=="" ||
           password==null || password=="" ||
           nickname==null || nickname=="" ||
           ageStr == null || ageStr == "" ||
           !ageStr.matches("[0-9]{1,3}")){
            try {
                /*
                    sendRedirect 重定向
                    使用响应对象要求浏览器重定向到指定位置
                    浏览器收到响应后, 就会根据该路径自动重新请求:
                    http://localhost:8080/reg_info_error.html
                 */
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        /*

         */


        int age = Integer.parseInt(ageStr);
        User user = new User(username,password,nickname,age);

        File file = new File(userDir, username+".obj");
        if(file.exists()){
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try (
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            ){
            oos.writeObject(user);

            //成功注册后
            response.sendRedirect("./reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户登录！！！！！！！");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username==null || username.isEmpty() ||
                password==null || username.isEmpty()){

            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
//        if(userDir.listFiles().length == 0){
//
//        }
        /*
            Flie file = new File(userDir,username+".obj");
            if(file.exist()){
                try(
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                ){
                     User user = ois.readObject();
                }
            }else{

            }



         */
        File[] subs = userDir.listFiles();
        File file = null;
        for(File sub : subs){
            System.out.println(Arrays.toString(sub.getName().split("\\.obj")));
            if(username.equals(sub.getName().split("\\.obj")[0])){
                file = sub;
                break;
            }
        }
        if(file != null){
            try (
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User)ois.readObject();
                if(password.equals(user.getPassword())){
                    try {
                        response.sendRedirect("login_success.html");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        response.sendRedirect("login_fail.html");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            try {
                response.sendRedirect("login_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理!");
        List<User> list = new ArrayList<>();
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));

        for(File sub : subs){
            try (
                FileInputStream fis = new FileInputStream(sub);
                ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                User user = (User)ois.readObject();
                list.add(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
//        list.forEach(new Consumer<User>() {
//            @Override
//            public void accept(User user) {
//
//            }
//        });
        list.forEach(System.out::println);

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("    <meta charset=\"UTF-8\">");
            pw.println("    <title>");
            pw.println("        用户列表");
            pw.println("    </title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("    <center>");
            pw.println("        <h1>用户列表</h1>");
            pw.println("        <table border=\"1\">");
            pw.println("            <tr align=\"center\">");
            pw.println("                <td width=\"100\">用户名</td>");
            pw.println("                <td width=\"100\">密码</td>");
            pw.println("                <td width=\"100\">昵称</td>");
            pw.println("                <td width=\"100\">年龄</td>");
            pw.println("            </tr>");
            for(User user : list){
                pw.println("        <tr align=\"center\">");
                pw.println("            <td>"+user.getUsername()+"</td>");
                pw.println("            <td>"+user.getPassword()+"</td>");
                pw.println("            <td>"+user.getNickname()+"</td>");
                pw.println("            <td>"+user.getNickname()+"</td>");
                pw.println("        </tr>");
            }
            pw.println("        <table>");
            pw.println("    </center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
